package com.xsherl.leetcode.solution;

import com.xsherl.leetcode.utils.PrintUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: sherl
 * @Date: 2021/5/24 20:50
 */
public class FourSum {

    /**
     * 外层循环，然后内层变成3数之和
     *
     * @param nums
     * 0 <= nums.length <= 200
     * -109 <= nums[i] <= 109
     * @param target
     * -109 <= target <= 109
     */
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < nums.length - 3; ++i){
            if (i > 0 && nums[i] == nums[i - 1]){
                continue;
            }
            for (int j = i + 1; j < nums.length - 2; ++j){
                if (j > i + 1 && nums[j] == nums[j - 1]){
                    continue;
                }
                int t = target - nums[i] - nums[j];
                int k  = j + 1, l = nums.length - 1;
                while (k < l){
                    if (k > j + 1 && nums[k] == nums[k - 1]){
                        k++;
                        continue;
                    }
                    if (l < nums.length - 1 && nums[l] == nums[l + 1]){
                        l--;
                        continue;
                    }
                    if (nums[k] + nums[l] < t){
                        k++;
                    } else if (nums[k] + nums[l] > t) {
                        l--;
                    } else {
                        res.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
                        k++;
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = {1,0,-1,0,-2,2};
        int target = 0;
        List<List<Integer>> lists = new FourSum().fourSum(nums, target);
        PrintUtils.println(lists);
    }

}
